package org.jeecg.modules.weeklyTasks.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.weeklyTasks.entity.WeekTasksDTO;
import org.jeecg.modules.weeklyTasks.entity.WeeklyTasks;
import org.jeecg.modules.weeklyTasks.service.IWeeklyTasksService;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @Description: 每周任务
 * @Author: jeecg-boot
 * @Date:   2023-12-21
 * @Version: V1.0
 */
@Api(tags="每周任务")
@RestController
@RequestMapping("/weeklyTasks/weeklyTasks")
@Slf4j
public class WeeklyTasksController extends JeecgController<WeeklyTasks, IWeeklyTasksService> {
	@Autowired
	private IWeeklyTasksService weeklyTasksService;
	
	/**
	 * 分页列表查询
	 *
	 * @param weeklyTasks
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "每周任务-分页列表查询")
	@ApiOperation(value="每周任务-分页列表查询", notes="每周任务-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(WeeklyTasks weeklyTasks,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<WeeklyTasks> queryWrapper = QueryGenerator.initQueryWrapper(weeklyTasks, req.getParameterMap());
		Page<WeeklyTasks> page = new Page<WeeklyTasks>(pageNo, pageSize);
		IPage<WeeklyTasks> pageList = weeklyTasksService.page(page, queryWrapper);
		List<WeekTasksDTO> dtoList = new ArrayList<>();
		try {
			for (WeeklyTasks weeklyTask : pageList.getRecords()) {
				WeekTasksDTO dto = getWeekTasksDTO(weeklyTask);
				dtoList.add(dto);
			}
		} catch (Exception e) {
			log.error("WeeklyTasksController.queryPageList()方法出现异常：",e);
			return Result.OK(pageList);
		}
		return Result.OK(dtoList);
	}

	@GetMapping("/getOwnerWeek")
	public Result<?> getOwnerWeek(){
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		Calendar calendar = Calendar.getInstance();
		int year = calendar.get(Calendar.YEAR);
		calendar.setFirstDayOfWeek(Calendar.MONDAY);
		int weekOfYear = calendar.get(Calendar.WEEK_OF_YEAR);
		LambdaQueryWrapper<WeeklyTasks> wrapper = Wrappers.lambdaQuery();
		wrapper.eq(WeeklyTasks::getUser, user.getRealname());
		wrapper.eq(WeeklyTasks::getYear, year);
		wrapper.eq(WeeklyTasks::getYearWeek, weekOfYear);
		wrapper.ne(WeeklyTasks::getProgress, 100);
		WeeklyTasks one = weeklyTasksService.getOne(wrapper);
		WeekTasksDTO weekTasksDTO = null;
		try {
			weekTasksDTO = getWeekTasksDTO(one);
		} catch (Exception e) {
			log.error("WeeklyTasksController.getByUser()方法出现异常：",e);
			return Result.OK(one);
		}
		return Result.OK(weekTasksDTO);
	}

	@GetMapping("/getByUser")
	public Result<?> getByUser(@RequestParam(name = "user")String user){
		Calendar calendar = Calendar.getInstance();
		int year = calendar.get(Calendar.YEAR);
		calendar.setFirstDayOfWeek(Calendar.MONDAY);
		int weekOfYear = calendar.get(Calendar.WEEK_OF_YEAR);
		LambdaQueryWrapper<WeeklyTasks> wrapper = Wrappers.lambdaQuery();
		wrapper.eq(WeeklyTasks::getUser, user);
		wrapper.eq(WeeklyTasks::getYear, year);
		wrapper.eq(WeeklyTasks::getYearWeek, weekOfYear);
		wrapper.ne(WeeklyTasks::getProgress, 100);
		WeeklyTasks one = weeklyTasksService.getOne(wrapper);
		WeekTasksDTO weekTasksDTO = null;
		try {
			weekTasksDTO = getWeekTasksDTO(one);
		} catch (Exception e) {
			log.error("WeeklyTasksController.getByUser()方法出现异常：",e);
			return Result.OK(one);
		}
		return Result.OK(weekTasksDTO);
	}

	@GetMapping("/getAll")
	public Result<?> getAll(){
		List<WeeklyTasks> list = weeklyTasksService.list();
		List<WeekTasksDTO> dtoList = null;
		try {
			dtoList = parseText(list);
		} catch (Exception e) {
			log.error("WeeklyTasksController.getAll()方法出现异常：",e);
			return Result.OK(list);
		}
		return Result.OK(dtoList);
	}

	@NotNull
	private static List<WeekTasksDTO> parseText(List<WeeklyTasks> list) {
		List<WeekTasksDTO> dtoList = new ArrayList<>();
		for (WeeklyTasks weeklyTask : list) {
			WeekTasksDTO dto = getWeekTasksDTO(weeklyTask);
			dtoList.add(dto);
		}
		return dtoList;
	}

	@NotNull
	private static WeekTasksDTO getWeekTasksDTO(WeeklyTasks weeklyTask) {
		WeekTasksDTO dto = new WeekTasksDTO();
		try {
			BeanUtils.copyProperties(weeklyTask, dto);
			String text = weeklyTask.getText().replaceAll("=", "\":\"");
			text = text.replaceAll("\\{", "{\"");
			text = text.replaceAll("\\}", "\"}");
			JSONArray jsonArray = JSON.parseArray(text);
			List<Map<String, Object>> list1 = new ArrayList<>();
			for (int i = 0; i < jsonArray.size(); i++) {
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				Map<String, Object> map = new HashMap<>(jsonObject.getInnerMap());
				list1.add(map);
			}
			dto.setAddArr(list1);
		} catch (BeansException e) {
			log.error("WeeklyTasksController.getWeekTasksDTO()方法出现异常：",e);
		}
		return dto;
	}

	/**
	 *   小程序页面添加
	 *
	 * @param weekTasksDTO
	 * @return
	 */
	@AutoLog(value = "每周任务-添加")
	@ApiOperation(value="每周任务-添加", notes="每周任务-添加")
	@PostMapping(value = "/appAdd")
	public Result<?> appAdd(@RequestBody WeekTasksDTO weekTasksDTO) {
		weekTasksDTO.setProgress(0);
		List<Map<String, Object>> addArr = weekTasksDTO.getAddArr();
		WeeklyTasks weeklyTasks = new WeeklyTasks();
		BeanUtils.copyProperties(weekTasksDTO, weeklyTasks);
		weeklyTasks.setText(String.valueOf(addArr));
		weeklyTasksService.save(weeklyTasks);
		return Result.OK("添加成功！");
	}
	
	/**
	 *   添加
	 *
	 * @param weeklyTasks
	 * @return
	 */
	@AutoLog(value = "每周任务-添加")
	@ApiOperation(value="每周任务-添加", notes="每周任务-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody WeeklyTasks weeklyTasks) {
		weeklyTasks.setProgress(0);
		weeklyTasksService.save(weeklyTasks);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param weeklyTasks
	 * @return
	 */
	@AutoLog(value = "每周任务-编辑")
	@ApiOperation(value="每周任务-编辑", notes="每周任务-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody WeeklyTasks weeklyTasks) {
		weeklyTasksService.updateById(weeklyTasks);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "每周任务-通过id删除")
	@ApiOperation(value="每周任务-通过id删除", notes="每周任务-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		weeklyTasksService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "每周任务-批量删除")
	@ApiOperation(value="每周任务-批量删除", notes="每周任务-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.weeklyTasksService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "每周任务-通过id查询")
	@ApiOperation(value="每周任务-通过id查询", notes="每周任务-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		WeeklyTasks weeklyTasks = weeklyTasksService.getById(id);
		if(weeklyTasks==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(weeklyTasks);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param weeklyTasks
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, WeeklyTasks weeklyTasks) {
        return super.exportXls(request, weeklyTasks, WeeklyTasks.class, "每周任务");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, WeeklyTasks.class);
    }

}
